package com.ch.doudemo.activity;

import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.ch.doudemo.R;
import com.ch.doudemo.adapter.SVideoCommentAdapter;
import com.ch.doudemo.base.BaseActivity;
import com.ch.doudemo.base.MyApp;
import com.ch.doudemo.bean.AddCommonReqBean;
import com.ch.doudemo.bean.CommonReqBean;
import com.ch.doudemo.bean.CommonResBean;
import com.ch.doudemo.bean.MessageBean;
import com.ch.doudemo.bean.UrlBean;
import com.ch.doudemo.bean.VideoDetailResBean;
import com.ch.doudemo.bean.VideoListResBean;
import com.ch.doudemo.util.AndroidUtil;
import com.ch.doudemo.util.HttpClientUtil;
import com.ch.doudemo.util.MyConstant;
import com.ch.doudemo.util.MyStringCallback;
import com.ch.doudemo.widget.MyVideoPlayer;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class SingleVideoActivity extends BaseActivity {

    /**
     * STR1 VideoListResBean.Responsebody intentVideoItem;
     * STR2 intentCommentNum评论数
     * STR3 intentGood  点赞数 以及状态
     * STR4 intentContent 标题
     */

    @BindView(R.id.singleVideoP)
    MyVideoPlayer singleVideoP;
    @BindView(R.id.singleVideoTV)
    TextView singleVideoTV;
    @BindView(R.id.dzBT)
    TextView dzBT;
    @BindView(R.id.plBT)
    TextView plBT;
    @BindView(R.id.allScreenBT)
    TextView allScreenBT;
    @BindView(R.id.plLL)
    FrameLayout plLL;
    @BindView(R.id.contentTV)
    TextView contentTV;
    @BindView(R.id.fbBT)
    Button fbBT;
    @BindView(R.id.content2TV)
    TextView content2TV;
    @BindView(R.id.pl2TV)
    TextView pl2TV;
    @BindView(R.id.dz2BT)
    TextView dz2BT;
    @BindView(R.id.plLV)
    ListView plLV;
    @BindView(R.id.replay2BT)
    TextView replay2BT;
    @BindView(R.id.inputFL)
    FrameLayout inputFL;
    @BindView(R.id.contentET)
    EditText contentET;
    @BindView(R.id.inputBGFL)
    FrameLayout inputBGFL;

    private VideoListResBean.Responsebody intentVideoItem;
    private MyApp myApp;
    private String intentCommentNum;//评论数
    private String intentGood;//评论数以及状态
    private String intentContent;//标题
    private SVideoCommentAdapter sVideoCommentAdapter;
    private VideoDetailResBean.Responsebody curItem;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_video);
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        init();
        requestVideoDetail();
    }


    private void init() {
        myApp = (MyApp) getApplication();
        intentVideoItem = (VideoListResBean.Responsebody) getIntent().getSerializableExtra(MyConstant.Str1);
        intentCommentNum = getIntent().getStringExtra(MyConstant.Str2);
        intentGood = getIntent().getStringExtra(MyConstant.Str3);
        intentContent = getIntent().getStringExtra(MyConstant.Str4);
        sVideoCommentAdapter = new SVideoCommentAdapter(this);
        plLV.setAdapter(sVideoCommentAdapter);
        singleVideoP.setUp(intentVideoItem.getV_url(), intentVideoItem.getUser_name() + intentVideoItem.getCreate_date(), MyVideoPlayer.STATE_NORMAL);
        Glide.with(this).load(intentVideoItem.getV_url()).into(singleVideoP.thumbImageView);
        singleVideoP.startVideo();
        dzBT.setText(intentGood);
        dz2BT.setText(intentGood);
        plBT.setText("评论" + intentCommentNum);
        pl2TV.setText("评论" + intentCommentNum);
        contentTV.setText(intentContent);
        content2TV.setText(intentContent);

    }


    private void requestVideoDetail() {
        CommonReqBean commonReqBean = new CommonReqBean();
        commonReqBean.setV_id(intentVideoItem.getId());
        String jsonStr = JSON.toJSONString(commonReqBean);
        HttpClientUtil.postReq(UrlBean.ReqVideoDetail, myApp.getToken(), jsonStr, this, new MyStringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(SingleVideoActivity.this, UrlBean.ReqError, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("response", "requestVideoDetail = " + response);
                VideoDetailResBean videoDetailResBean = JSON.parseObject(response, VideoDetailResBean.class);
                if ("0".equals(videoDetailResBean.getErrcode())) {
                    if (null != videoDetailResBean.getData() && 0 != videoDetailResBean.getData().size()) {
                        sVideoCommentAdapter.setItems(videoDetailResBean.getData());
                    }
                } else {
                    Toast.makeText(SingleVideoActivity.this, videoDetailResBean.getErrmsg(), Toast.LENGTH_SHORT).show();
                }
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        MyVideoPlayer.goOnPlayOnResume();//从停止处继续播放
    }


    @Override
    public void onPause() {
        super.onPause();
        MyVideoPlayer.goOnPlayOnPause();//停止播放的位置
//        MyVideoPlayer.releaseAllVideos(); //释放所有videos
    }

    @OnClick({R.id.dzBT, R.id.dz2BT, R.id.plBT, R.id.allScreenBT, R.id.replay2BT, R.id.fbBT, R.id.inputBGFL})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dzBT:
            case R.id.dz2BT:
                requestGood();
                break;
            case R.id.plBT:
                singleVideoP.post(new Runnable() {
                    @Override
                    public void run() {
                        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) singleVideoP.getLayoutParams();
                        params.height = dpToPx(200);
                        singleVideoP.setLayoutParams(params);
                        plLL.setVisibility(View.VISIBLE);
                    }
                });
                break;
            case R.id.allScreenBT:
                singleVideoP.post(new Runnable() {
                    @Override
                    public void run() {
                        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) singleVideoP.getLayoutParams();
                        params.height = FrameLayout.LayoutParams.MATCH_PARENT;
                        singleVideoP.setLayoutParams(params);
                        plLL.setVisibility(View.GONE);
                    }
                });
                break;
            case R.id.replay2BT:
                showInputLayout(getString(R.string.pinglun_sign), null);
                break;
            case R.id.fbBT:
                if (contentET.getText().toString().trim().equals("")) {
                    closeInputLayout();
                } else {
                    //请求评论 / 回复
                    requestAddComment();
                }
                break;
            case R.id.inputBGFL:
                closeInputLayout();
                break;
        }
    }

    public static int dpToPx(int dp) {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
    }

    public void showInputLayout(String pStr, VideoDetailResBean.Responsebody pItemBody) {
        this.curItem = pItemBody;
        inputBGFL.setVisibility(View.VISIBLE);
        inputFL.setVisibility(View.VISIBLE);
        contentET.setHint(pStr);
    }


    /**
     * 评论点赞
     */
    private void requestGood() {
        String reqUrl;
        //此处简单一写 只为了获取点赞数量显示  这么写肯定不好~ 根据具体需求处理
        int curGoodNum = Integer.parseInt(dzBT.getText().toString().replace("♡点赞", "").replace("♥已赞", ""));
        if (dzBT.getText().toString().contains("♥")) {
            reqUrl = UrlBean.ReqCancelGood;
        } else {
            reqUrl = UrlBean.ReqAddGood;
        }
        CommonReqBean commonReqBean = new CommonReqBean();
        commonReqBean.setV_id(intentVideoItem.getId());
        String jsonStr = JSON.toJSONString(commonReqBean);
        HttpClientUtil.postReq(reqUrl, myApp.getToken(), jsonStr, this, new MyStringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                CommonResBean commonResBean = JSON.parseObject(response, CommonResBean.class);
                if ("0".equals(commonResBean.getErrcode())) {
                    if (dzBT.getText().toString().contains("♥")) {
                        dzBT.setText("♡点赞" + (curGoodNum - 1) + "");
                        dz2BT.setText("♡点赞" + (curGoodNum - 1) + "");
                    } else {
                        dzBT.setText("♥已赞" + (curGoodNum + 1) + "");
                        dz2BT.setText("♥已赞" + (curGoodNum + 1) + "");
                    }
                    EventBus.getDefault().post(new MessageBean(MyConstant.Msg1, dzBT.getText().toString()));

                }

            }
        });

    }


    /**
     * 子评论点赞
     *
     * @param pCID
     * @param pTV
     * @param pTVStr
     * @param pGoodNum
     */
    public void requestChildGood(String pCID, TextView pTV, String pTVStr, int pGoodNum) {
        String reqUrl;
        //此处简单一写 只为了获取点赞数量显示  这么写肯定不好~ 根据具体需求处理
        CommonReqBean commonReqBean = new CommonReqBean();
        if (pTVStr.contains("♥")) {
            reqUrl = UrlBean.ReqCancelChildGood;
        } else {
            reqUrl = UrlBean.ReqAddChildGood;
        }
        commonReqBean.setC_id(pCID);
        String jsonStr = JSON.toJSONString(commonReqBean);
        HttpClientUtil.postReq(reqUrl, myApp.getToken(), jsonStr, this, new MyStringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                CommonResBean commonResBean = JSON.parseObject(response, CommonResBean.class);
                if ("0".equals(commonResBean.getErrcode())) {
                    if (pTV.getText().toString().contains("♥")) {
                        pTV.setText("♡点赞" + (pGoodNum - 1) + "");
                    } else {
                        pTV.setText("♥已赞" + (pGoodNum + 1) + "");
                    }
                }

            }
        });
    }


    private void requestAddComment() {
        AddCommonReqBean addCommonReqBean = new AddCommonReqBean();
        addCommonReqBean.setV_id(intentVideoItem.getId());
        addCommonReqBean.setContent(contentET.getText().toString());
        if (getString(R.string.huifu_sign).equals(contentET.getHint().toString()) && null != curItem) {
            addCommonReqBean.setStart_id(curItem.getId());
            addCommonReqBean.setComment_id(curItem.getComment_id());
            addCommonReqBean.setCover_user_id(curItem.getUser_id());
            addCommonReqBean.setCover_user_name(curItem.getUser_name());
        }
        String jsonStr = JSON.toJSONString(addCommonReqBean);
        HttpClientUtil.postReq(UrlBean.ReqAddComment, myApp.getToken(), jsonStr, this, new MyStringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                CommonResBean commonResBean = JSON.parseObject(response, CommonResBean.class);
                if ("0".equals(commonResBean.getErrcode())) {
                    closeInputLayout();
                    requestVideoDetail();
                }

            }
        });
    }


    /**
     * 关闭输入框布局
     */
    private void closeInputLayout(){
        inputFL.setVisibility(View.GONE);
        inputBGFL.setVisibility(View.GONE);
        AndroidUtil.softInputStateHidden(SingleVideoActivity.this);
        contentET.setText("");
        contentET.setHint("");
    }

}
